package com.dna.okangjang.main.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.dna.okangjang.main.dao.DaumApiDao;
import com.dna.okangjang.main.dao.NaverApiDao;
import com.dna.okangjang.main.model.DBlog;
import com.dna.okangjang.main.model.DCafe;
import com.dna.okangjang.main.model.DImage;
import com.dna.okangjang.main.model.NImage;
import com.dna.okangjang.main.model.SearchResult;
import com.dna.okangjang.main.service.MainService;

@Service("mainService")
public class MainServiceImpl implements MainService {
	private static final Log logger = LogFactory.getLog(MainServiceImpl.class);
	
	private static final String QUERY = "공동구매";
	private static final String DEFAULT_IMG_URL = "http://imgmovie.naver.com/mdi/mi/0788/78853_S04_150447.jpg";
	
	private static final int IMG_API_PAGE = 1;
	private static final int IMG_API_ROW = 5;
	
	@Resource
	private DaumApiDao daumApiDao;
	
	@Resource
	private NaverApiDao naverApiDao;
	
	private String makeSearchWord(String str){
		String[] regexList = new String[]{"\\[", "\\]", "공동구매", "공지", "이벤트", "진행", "진행중",
				"종료", "입니다", "공구", "예고", "마감", "최저", "최저가", "카페", "가격", "추진"};
		for(String regex : regexList){
			str = str.replaceAll(regex, "");
		}
		return str;
	}
	
	private String getImgUrl(String query){
		List<DImage> d_imgs = daumApiDao.getSearchImage(query, IMG_API_PAGE, IMG_API_ROW);
		if(d_imgs != null && d_imgs.size() != 0){
			//return d_imgs.get(0).getThumbnail();
			return d_imgs.get(0).getImage();
		}
		
		List<NImage> n_imgs = naverApiDao.getSearchImage(query, IMG_API_PAGE, IMG_API_ROW);
		if(n_imgs != null && n_imgs.size() != 0){
			return n_imgs.get(0).getThumbnail();
		}
		
		return DEFAULT_IMG_URL;
	}
	
	private List<SearchResult> getBlogSearch(String query, int page, int row){
		List<DBlog> list = daumApiDao.getSearchBlog(query, page, row);
		List<SearchResult> resultList = new ArrayList<SearchResult>();
		for(DBlog blog : list){
			SearchResult res = new SearchResult();
			res.setTitle(blog.getTitle());
			res.setLink(blog.getLink());
			res.setDescription(blog.getDescription());
			res.setPubDate(blog.getPubDate());
			
			String search_word = this.makeSearchWord(blog.getTitle());
			String imgUrl = this.getImgUrl(search_word);
			res.setImgUrl(imgUrl);
			
			res.setTarget("blog");
			res.setAuthor(blog.getAuthor());
			resultList.add(res);
		}
		
		return resultList;
	}
	
	private List<SearchResult> getCafeSearch(String query, int page, int row){
		List<DCafe> list = daumApiDao.getSearchCafe(query, page, row);
		List<SearchResult> resultList = new ArrayList<SearchResult>();
		for(DCafe cafe : list){
			SearchResult res = new SearchResult();
			res.setTitle(cafe.getTitle());
			res.setLink(cafe.getLink());
			res.setDescription(cafe.getDescription());
			res.setPubDate(cafe.getPubDate());
			
			String search_word = this.makeSearchWord(cafe.getTitle());
			String imgUrl = this.getImgUrl(search_word);
			res.setImgUrl(imgUrl);
			
			res.setTarget("cafe");
			res.setAuthor(cafe.getCafeName());
			resultList.add(res);
		}
		
		return resultList;
	}
	
	@Override
	public List<SearchResult> getBlogSearch(int page, int row) {
		return this.getBlogSearch(QUERY, page, row);
	}

	@Override
	public List<SearchResult> getCafeSearch(int page, int row) {
		return this.getCafeSearch(QUERY, page, row);
	}

	@Override
	public List<SearchResult> getBlogKeywordSearch(String query, int page, int row) {
		return this.getBlogSearch(query+" "+QUERY, page, row);
	}

	@Override
	public List<SearchResult> getCafeKeywordSearch(String query, int page, int row) {
		return this.getCafeSearch(query+" "+QUERY, page, row);
	}
	
	private static String downloadURL(String addr){
		String doc = "";
		try{
			URL url = new URL(addr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			if(conn != null){
				conn.setConnectTimeout(10000);
				conn.setUseCaches(false);
				if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
					BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
					for(;;){
						String line = br.readLine();
						if(line == null){
							break;
						}
						doc += line;
					}
					br.close();
				}
			}
		} catch(Exception e){
			e.printStackTrace();
		}
		
		return doc;
	}

}
